import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_rider/event/refresh_outside_list_event.dart';
import 'package:flutter_rider/generated/assets.dart';
import 'package:flutter_rider/kit/loc_kit.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/main/widgets/base/search_widget.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/ext/u_title_layout.dart';
import 'package:flutter_rider/main/widgets/state/refreshable_layout.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/module/mine/api/truck_api.dart';
import 'package:flutter_rider/module/mine/mine_router.dart';
import 'package:flutter_rider/module/mine/models/truck_model.dart';
import 'package:flutter_rider/module/mine/provider/outside_car_provider.dart';
import 'package:flutter_rider/routers/fluro_navigator.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_svg/parser.dart';

class OutsideCarPage extends ConsumerStatefulWidget {
  const OutsideCarPage({Key? key}) : super(key: key);

  @override
  ConsumerState<OutsideCarPage> createState() => _OutsideCarPageState();
}

class _OutsideCarPageState extends ConsumerState<OutsideCarPage> {
  final _stateController = RefreshableLayoutController();
  final _inputController = TextEditingController(text: "");
  late StreamSubscription _eventFn1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _eventFn1 = eventBus.on<RefreshOutsideList>().listen((event) {
      _stateController.reload();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _eventFn1.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: UIColor.color_main,
        appBar: UTitleLayout.getBackTitleRight(context, "场外车辆", "新增", () {
          Log.i("新增");
          NavigatorUtils.push(context, MineRouter.outsideCarDetailPage,
              arguments: {"isAddCar": true});
        }),
        body: SafeArea(
            child: Column(
          children: [
            // Container(
            //   color: UIColor.color_bg,
            //   child: Row(children: [
            //     16.wspace,
            //     SvgPicture.asset(Assets.imageVolumeHigh,
            //             width: 20.rpx, height: 20.rpx)
            //         .padding(EdgeInsets.only(top: 13.rpx, bottom: 13.rpx)),
            //     8.wspace,
            //     UText.get("场外车牌信息只展示今日数据", UIColor.color_primary, 14.rpx),
            //   ]),
            // ),
            SearchWidget(
              "搜索车牌号、提交人",
              textEditingController: _inputController,
              onEditingComplete: () {
                _stateController.reload();
              },
            ),
            _renderList(),
          ],
        )));
  }

  Widget _renderList() {
    return Expanded(
        child: RefreshableLayout(
            controller: _stateController,
            urlCallback: _buildUrl,
            handleDataCallback: _handleData,
            itemBuilder: _renderListItem));
  }

  String _buildUrl() {
    var baseUrl = TruckApi.truckList;
    var searchKey = _inputController.text.trim();
    if (searchKey.isNotEmpty) {
      if (!baseUrl.contains("?")) {
        baseUrl += "?";
      } else {
        baseUrl += "&";
      }
      baseUrl += "key=${Uri.encodeComponent(searchKey)}";
    }
    return baseUrl;
  }

  _handleData(dynamic list) {
    return list.map((e) => TruckModel.fromMap(e)).toList();
  }

  Widget _renderListItem(dynamic data, int index) {
    var truck = data as TruckModel;

    var list = truck.plate_no.split("");
    var plateNo = "";
    for (var i = 0; i < list.length; i++) {
      plateNo += list[i];
      if (i == 1) {
        plateNo += "·";
      }
    }

    return GestureDetector(
      onTap: () {
        NavigatorUtils.push(context, MineRouter.outsideCarDetailPage,
            arguments: {"truck": truck});
      },
      child: Container(
        decoration: BoxDecoration(
          color: UIColor.color_content,
          borderRadius: BorderRadius.circular(12.rpx),
        ),
        margin: EdgeInsets.only(top: 10.rpx, left: 12.rpx, right: 12.rpx),
        child: Column(
          children: [
            Row(
              // mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                UText.get(plateNo, UIColor.color_primary, 16.rpx,
                    fw: FontWeight.w500),
                const Spacer(),
                Icon(Icons.navigate_next,
                    size: 20.rpx, color: UIColor.color_t3),
              ],
            ),
            13.hspace,
            Row(
              // mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SvgPicture.asset(Assets.imageUserEdit,
                    width: 20.rpx, height: 20.rpx),
                5.wspace,
                UText.get(
                  truck.user_name,
                  UIColor.color_t3,
                  14.rpx,
                ).expand,
              ],
            ),
            10.hspace,
            Row(
              // mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SvgPicture.asset(Assets.imageCarLocation,
                    width: 20.rpx, height: 20.rpx),
                5.wspace,
                UText.get(
                  truck.park_name,
                  UIColor.color_t3,
                  14.rpx,
                ).expand,
              ],
            ),
            10.hspace,
            Row(
              // mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SvgPicture.asset(Assets.imageCarClock,
                    width: 20.rpx, height: 20.rpx),
                5.wspace,
                UText.get(
                  truck.creat_at,
                  UIColor.color_t3,
                  14.rpx,
                ),
              ],
            ),
          ],
        ).padding(EdgeInsets.all(16.rpx)),
      ),
    );
  }
}
